package com.moyu.user.service.impl;

import cn.hutool.core.lang.TypeReference;
import com.moyu.common.core.contants.CacheConstants;
import com.moyu.common.core.domain.R;
import com.moyu.common.redis.service.RedisService;
import com.moyu.user.service.IStatsService;
import org.springframework.data.redis.core.Cursor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author 赵彦博
 * @Date 2025/3/30 14:42
 */
@Service
public class StatsServiceImpl implements IStatsService {


    @Autowired
    private RedisService redisService;

    // 获取当前在线用户数（基于活跃Token）
    public Long getOnlineCount() {
        String pattern = CacheConstants.LOGIN_TOKEN_KEY + "*";
        long count = 0;

        Cursor<String> cursor = redisService.scan(pattern);
        while (cursor.hasNext()) {
            cursor.next();
            count++;
        }
        return count;
    }

    // 获取总访问量（基于Token创建记录）
    public Long getTotalVisits() {
        String key = "stats:total_visits";
        Long visits = redisService.getCacheObject(key, Long.class);
        return visits != null ? visits : 0;
    }

    @Override
    public List<Map<String, Object>> getRecentLogins() {
        List<Map> rawList = redisService.getListRange(
                "recent:logins",
                0,
                19,
                Map.class
        );

        // 手动转换类型
        return rawList.stream()
                .map(map -> (Map<String, Object>) map)
                .peek(login -> {
                    long timestamp = (long) login.get("time");
                    login.put("time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                            .format(new Date(timestamp)));
                })
                .collect(Collectors.toList());
    }
}
